package com.vcc.web.core.queue.pingpong.queue;

import com.vcc.data.entity.CardType;
import com.vcc.service.service.*;
import com.vcc.web.core.component.PingPongComponent;
import com.vcc.web.core.queue.pingpong.model.OpenCard;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Executors;

@Component
public class OpenCardQueue implements CommandLineRunner {

    @Autowired
    private PingPongComponent pingPongComponent;
    @Autowired
    private UserService userService;
    @Autowired
    private UserCardService userCardService;
    @Autowired
    private UserCardWalletService userCardWalletService;
    @Autowired
    private CardTypeService cardService;
    @Autowired
    private WalletDetailService walletDetailService;
    @Autowired
    private WalletService walletService;


    private static final Logger logger = LoggerFactory.getLogger(OpenCardQueue.class);

    private volatile DelayQueue<OpenCard> delayQueue = new DelayQueue<OpenCard>();


    public void add(String orderId, Long userId, Long cardId, String ppCardId, BigDecimal amount, String remark,Long cardholderId) {
        synchronized (this) {
            OpenCard openCard = delayQueue.stream().filter(it -> it.getPpCardId().equals(ppCardId)).findFirst().orElse(null);
            if (openCard == null) {
                LocalDateTime now = LocalDateTime.now();
                LocalDateTime nowB = now.plusSeconds(5L);
                long betweenMillis = ChronoUnit.MILLIS.between(now, nowB);
                logger.info("当前添加的是{},秒{}",orderId ,5);
                delayQueue.put(
                        new OpenCard(
                                ppCardId, betweenMillis, cardId, userId, orderId, amount, remark,cardholderId
                        )
                );
            }
        }
    }


    @Override
    public void run(String... args) throws Exception {
        Executors.newSingleThreadExecutor().execute(new Thread(this::excuteThread));
    }

    private void excuteThread() {
        while (true) {
            try {
                processTask(delayQueue.take());
            } catch (InterruptedException e) {
                break;
            }
        }
    }

    /**
     * 内部执行延时任务
     *
     * @param openCard
     */
    private void processTask(OpenCard openCard) {
        try{
            logger.info("当前处理的卡是{}", openCard.getPpCardId());
//            User user = userService.getById(openCard.getUserId());
            CardType card = cardService.getById(openCard.getCardId());
//            CardDetail2 cardInfo = pingPongComponent.getCardInfo(openCard.getPpCardId());
//            UserCard userCard = new UserCard();
//            userCard.setCardNumber(cardInfo.getCardNumber());
//            userCard.setCardNumberLastFour(cardInfo.getCardNumber().substring(cardInfo.getCardNumber().length() - 4));
//            userCard.setVcc(cardInfo.getCvc());
//            userCard.setExpiry(cardInfo.getExpiry());
//            userCard.setRequestDate(new Date());
//            userCard.setOrderId(openCard.getOrderId());
//            userCard.setCardId(openCard.getCardId());
//            userCard.setUserId(openCard.getUserId());
//            userCard.setChannelCardId(openCard.getPpCardId());
//            userCard.setChannelCode(card.getCode());
//            userCard.setCurrencyCode(card.getCurrencyCode());
//            userCard.setCurrencyName(card.getCurrencyName());
//            userCard.setCardType(card.getCardLabel());
//            userCard.setUsableQuota(BigDecimal.valueOf(0));
//            userCard.setRemark(openCard.getRemark());
//            userCard.setCardStatus("ACTIVE");
//            userCard.setSumCount(0);
//            userCard.setSuccessCount(0);
//            userCard.setErrorCount(0);
//            userCard.setSumAmount(BigDecimal.valueOf(0));
//            userCard.setSuccessAmount(BigDecimal.valueOf(0));
//            userCard.setErrorAmount(BigDecimal.valueOf(0));
//            userCard.setCardholderId(openCard.getCardholderId());
//            userCardService.save(userCard);
//            String orderId = IdWorker.getStringOrderId();
//            if (Objects.equals(openCard.getAmount().compareTo(BigDecimal.valueOf(0)), 1)) {
//                pingPongComponent.recharge(orderId, openCard.getRemark(), userCard, openCard.getAmount());
//            }
        }catch (Exception e){
            logger.error("异常",e);
        }
    }
}
